package top.xunfong.file.controller;


import top.xunfong.common.core.domain.R;
import top.xunfong.file.domain.dto.BreakpointDTO;
import top.xunfong.file.domain.vo.BreakpointCheckVO;
import top.xunfong.file.domain.vo.BreakpointMergeVO;
import top.xunfong.file.domain.vo.FileVO;
import top.xunfong.file.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;


/**
 * 文件上传
 */
@RestController
@RequestMapping(value = "/upload")
public class FileController {

    @Autowired
    private FileService fileService;

    /**
     * 单文件上传
     *
     * @param file
     * @return
     */
    @PostMapping("/single")
    public R<FileVO> upload(MultipartFile file) {
        try {
            return R.ok(fileService.upload(file));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 断点续传分片
     *
     * @param dto
     * @return
     */
    @RequestMapping(value = "/breakpoint/chunk", method = {RequestMethod.POST, RequestMethod.OPTIONS})
    public R<FileVO> breakpoint(BreakpointDTO dto, MultipartFile file) {
        try {
            fileService.breakpoint(dto, file);
            return R.ok();
        } catch (IOException e) {
            return R.fail();
        }
    }

    @PostMapping("/breakpoint/check")
    public R<BreakpointCheckVO> breakpointCheck(@RequestBody BreakpointDTO dto) {
        BreakpointCheckVO breakpointCheckVO = fileService.breakpointCheck(dto);
        return R.ok(breakpointCheckVO);
    }

    /**
     * 断点续传合并
     *
     * @param dto
     * @return
     */
    @PostMapping("/breakpoint/merge")
    public R<BreakpointMergeVO> breakpointMerge(@RequestBody BreakpointDTO dto) {
        return R.ok(fileService.breakpointComplete(dto));
    }
}
